import json

from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from rest_framework import pagination, generics
from rest_framework.views import APIView
from apps.goods.models import Goods
from apps.goods.serializers import GoodsSerializer
from utils import ResponseMessage


# http://localhost:8000/goods/category_id/page_id
class GoodsCategoryAPIView(APIView):
    def get(self, request, category_id, page_id):
        # if not request.user.get("status"):
        #     return JsonResponse("request.user", safe=False)
        current_page = (page_id - 1) * 5  #当前页的起始位置
        end_page = page_id * 5  #当前页的结束位置
        category_data = Goods.objects.filter(
            type_id=category_id
        )[current_page:end_page]
        # print(type(category_data))
        return ResponseMessage.GoodsResponse.success(category_data)

# http://localhost:8000/goods/sku_id
class GoodsDetailAPIView(APIView):
    # def get(self, request, sku_id):
    #     # good_data = Goods.objects.filter(sku_id=sku_id)  # 返回的是一个QuerySet查询集，并不是一个对象
    #     good_data = Goods.objects.filter(sku_id=sku_id).first()  # 获取 QuerySet 中的第一个模型实例，是一个对象
    #     print(type(good_data))
    #     # 序列化的参数是instance，反序列化的参数是data
    #     result = GoodsSerializer(instance=good_data)
    #     result_json = {'status': '2000', 'data': result.data}
    #     # print(result)
    #     # print(result.data)
    #     return HttpResponse(json.dumps(result_json), content_type='application/json')

    def get(self, request, sku_id):
        good_data = Goods.objects.filter(sku_id=sku_id)
        print(type(good_data))
        # 设置 many=True 表示告诉序列化器要处理多个对象也就是传入的instance是一个包含多个对象的查询集，通常用于处理查询集（QuerySet）返回的结果
        result = GoodsSerializer(instance=good_data, many=True)
        result_json = {'status': '2000', 'data': result.data}
        return HttpResponse(json.dumps(result_json), content_type='application/json')

class GoodsSearchAPIView(APIView):
    def get(self, request, keyword, page):
        current_page = (int(page) - 1) * 5
        end_page = page * 5  # 当前页的结束位置
        category_data = Goods.objects.filter(
            Q(name__icontains=keyword)
        )[current_page:end_page]
        if not category_data:
            return ResponseMessage.GoodsListResponse.other('数据不存在')
        serializer = GoodsSerializer(category_data, many=True)
        print(serializer.data)
        return ResponseMessage.GoodsListResponse.success(serializer.data)
